package com.sky.agent.utils;

import cn.hutool.core.codec.Base64;
import com.beust.ah.A;
import com.sky.agent.config.Contants;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * @description: 对原始数据进行AES加密后，再进行十六进制转化；
 **/
@Slf4j
public class AESUtil {

    private static Object lock = new Object();
    private static final String GAODE_PKCS5 = "AES/CBC/PKCS5Padding";
    private static final String AES = "AES";
    private static Cipher encipher = null;
    private static Cipher decipher = null;

    public AESUtil() {
        try {
            SecretKeySpec skeySpec = new SecretKeySpec(Contants.VALUE, AES);
            IvParameterSpec iv = new IvParameterSpec(Contants.PARAMS);

            encipher = Cipher.getInstance(GAODE_PKCS5);
            encipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            decipher = Cipher.getInstance(GAODE_PKCS5);
            decipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        } catch (Exception e) {
            log.error("GaoDeAESUtil,Exception:{}", e);
        }
    }

    public static String decrypt(String sSrc) throws Exception {
        AESUtil aes = new AESUtil();
        byte[] encrypted1 = hexStringToBytes(sSrc);
        byte[] original = null;
        synchronized (lock) {
            original = decipher.doFinal(encrypted1);
        }
        String originalString = new String(original, StandardCharsets.UTF_8);
        return originalString;
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    public static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}